//
//  HomeVC_V2.swift
//  LeGou
//
//  Created by lxm on 2022/9/19.
//

import UIKit
import JXPagingView
import JXSegmentedView
class HomeVC_V2: ZMViewController, JXSegmentedViewDelegate, SDCycleScrollViewDelegate {
    //MARK: --------------------属性--------------------
    let dataSource: HomeSegDataSource = HomeSegDataSource()
        
    var headerInSectionHeight: Int = 58
        
    var cateArr = [HomeGoodsCategory]()
    
    var bannerInfos = [HomeModels.BannerInfo]()
    
    let timer = Observable<Int>.timer(.seconds(0), period: .seconds(1), scheduler: MainScheduler.instance)

    //MARK: --------------------UI控件--------------------
        
    @IBOutlet weak var loginView: UIView!

    lazy var pagingView: JXPagingView = preferredPagingView()
    
    lazy var userHeaderView : HomeHeaderView = {
        let v = HomeHeaderView()
        return v
    }()
    
    lazy var vcs = preferredPagingViewVC()

    lazy var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: CGFloat(headerInSectionHeight)))

    let bgImg = ZMUtil.imageView(imageName: "home_bg")
    
    let navView = HomeNavView()
    
    // banner
    var bannerView: BannerContentView {
        get {
            userHeaderView.bannerView
        }
    }
    
    // 首页分类
    var homeCate: HomeCateView {
        get {
            userHeaderView.homeCate
        }
    }
    
    // 任务
    var someItemView: HomeTaskView {
        get {
            userHeaderView.homeTaskView
        }
    }
    
    var poolView: ConsumePoolView {
        get {
            userHeaderView.poolView
        }
    }



    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        bindAction()
        
        _ = LoginService.shared.checkIsInfoOk()
        if !AppHelper.appVerify() {
            ZMNewVersion.share.checkVersion()
        }
        loadBanner()

    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if !AppHelper.appVerify() {
            getPast()
            getPoolData()
            RedBagService.shared.getRedBagInfo()
        }
    }

    
    //MARK: --------------------UI--------------------
    func setUI() {
        //TODO: 看应该传什么类型过去
        cateArr = [HomeGoodsCategory(cname: "热门推荐", subTitlte: "猜你喜欢", type: .tb_list(typeEnum: "HEIGHT_COMMISSION")),
                   HomeGoodsCategory(cname: "淘宝", subTitlte: "超高返利", type: .tb_list(typeEnum: "EXPLOSIVE")),
                   HomeGoodsCategory(cname: "拼多多", subTitlte: "百亿补贴", type: .pdd),
                   HomeGoodsCategory(cname: "京东", subTitlte: "实时热销", type: .jd)
                   ]
        
        view.insertSubview(bgImg, at: 0)
        
        view.addSubview(navView)
        
        self.loginView.clipsToBounds = false
        self.loginView.layer.masksToBounds = false
        
        hbd_barHidden = true
//        dataSource.itemWidth = rpx(70)
        dataSource.isItemSpacingAverageEnabled = true
        dataSource.datas = cateArr.map({($0.cname, $0.subTitlte)})
        dataSource.itemSpacing = 26
        
        //配置指示器

        segmentedView.backgroundColor = "#F2F3F6".zm.hex()
        segmentedView.delegate = self
//        segmentedView.isContentScrollViewClickTransitionAnimationEnabled = false
        segmentedView.dataSource = dataSource
        segmentedView.backgroundColor = "#F5F5F5".zm.hex()
        segmentedView.contentEdgeInsetLeft = 22
        segmentedView.contentEdgeInsetRight = 22
        segmentedView.reloadData()
        pagingView.mainTableView.gestureDelegate = self
        self.view.addSubview(pagingView)
        
        segmentedView.listContainer = pagingView.listContainerView
        
        //扣边返回处理，下面的代码要加上
        pagingView.listContainerView.scrollView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
        pagingView.mainTableView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
        pagingView.mainTableView.backgroundColor = .clear
        
        addRefresh(scrollView: pagingView.mainTableView, addHead: true, addFoot: false) { [weak self] (refresh) in
            guard let self = self else {return}
            let vc = self.vcs[self.segmentedView.selectedIndex]
            if let jdVc = vc as? HomeJDListVC {
                jdVc.page = 1
                jdVc.loadList {
                    self.pagingView.mainTableView.mj_header?.endRefreshing()
                }
            } else if let tbVc = vc as? HomeListVC {
                tbVc.page = 1
                tbVc.loadList {
                    self.pagingView.mainTableView.mj_header?.endRefreshing()
                }
            } else if let tbVc = vc as? HomePDDListVC {
                tbVc.page = 1
                tbVc.loadList {
                    self.pagingView.mainTableView.mj_header?.endRefreshing()
                }
            }
            if self.bannerInfos.count == 0 {
                self.loadBanner()
            }
            RedBagService.shared.getRedBagInfo()
            self.userHeaderView.messageView.getInfo()
        }
        
        addConstraints()
//        showRedRain()
    }
    
    func addConstraints() {
        bgImg.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
        }
        
        navView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.left.equalTo(view).offset(12)
            make.right.equalTo(view).offset(-12)
            make.height.equalTo(44)
        }
        
        pagingView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.right.left.bottom.equalToSuperview()
//            make.edges.equalToSuperview()
        }
    }

    //MARK: --------------------methods--------------------
    func getPast() {
        if let user = ZMAppShareData.share.userInfo.value, user.relationId != "" {
            let UIPasteboardStr = (UserDefaults.standard.object(forKey: "UIPasteboardStr") as? String) ?? ""
            if let str = UIPasteboard.general.string, str != "", str != UIPasteboardStr, str.count < 250 {
                ZMLog(message: "当前粘贴板内容:\(str)")
                UserDefaults.standard.set(str, forKey: "UIPasteboardStr")
                HomeAPI.change_link(str).rxRequestNullAble(type: TBKouLingInfo.self).subscribe(onNext:{ resp in
                    if let data = resp, data.tbGoods != nil {
                        let v = ZMUtil.loadNibViewFullScreen(nibName: TBPasteboardSearchView.self)
                        v.setUI(data)
                        APPWindow?.addSubview(v)
                    } else {
                        let v = ZMUtil.loadNibViewFullScreen(nibName: TBPasteboardSearchErrView.self)
                        v.setUI(str)
                        APPWindow?.addSubview(v)
                    }
                }).disposed(by: disposeBag)
            }            
        }
    }
    // 获取奖池data
    func getPoolData() {
        HomeAPI.consumePool.rxRequest(type: Double.self).subscribe(onNext:{ [unowned self] resp in
            self.poolView.money.text = resp.zm.toString(keep: 2)
        }).disposed(by: disposeBag)
    }
        
    func bindAction() {
        timer.subscribe(onNext:{ [unowned self] resp in
            RedBagService.shared.checkNeedAutoRefresh()
            self.userHeaderView.redView.label.text = RedBagService.shared.getDes()
                RedBagService.shared.checkNeedShowRedRain()
        }).disposed(by: disposeBag)
        
        navView.searchButton.rx.tap.subscribe(onNext:{ [unowned self] resp in
            let vc = ZMSearchVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }).disposed(by: disposeBag)
        
        homeCate.cateView.itemClick = { (_, cate) in
            if cate == .phoneCharge {
                if LoginService.shared.checkLogin() == false {return}
                router.push("xm://main/telephone/chare")
            } else if cate == .tasks {
                if LoginService.shared.checkLogin() == false {return}
                let vc = GameWeb()
                vc.url = getgameUrl(userId: ZMAppShareData.share.safeUserId)
                self.navigationController?.pushViewController(vc, animated: true)
            } else if cate == .mt {
                let vc = MtTemp()
                self.navigationController?.pushViewController(vc, animated: true)
            } else if cate == .elm {
                let vc = MtTemp()
                vc.isMt = false
                self.navigationController?.pushViewController(vc, animated: true)
            } else if cate == .JD {
                let vc = JDCateVC()
                self.navigationController?.pushViewController(vc, animated: true)
            } else if cate == .taobao || cate == .U99 || cate == .heighFee {
                let vc = CateGoodsList()
                vc.type = cate
                self.navigationController?.pushViewController(vc, animated: true)
            } else if cate == .power {
                self.navigationController?.pushViewController(PowerVC(), animated:   true)
            } else if cate == .zeroBuy {
                self.navigationController?.pushViewController(NewBuyVC(), animated: true)
            } else if cate == .PDD {
                self.navigationController?.pushViewController(PddCateVC(), animated: true)
            } else if cate == .school {
                self.navigationController?.pushViewController(SchoolVC(), animated: true)
            } else if cate == .douyin {
                if LoginService.shared.checkLogin() == false {return}
                ZMToast.showActivity()
                HomeAPI.douYin([:]).rxRequest(type: String.self).subscribe(onNext:{ [unowned self] resp in
                    ZMToast.hiddenActivity()
                    if let url = URL(string: resp) {
                        if #available(iOS 10, *) {
                            UIApplication.shared.open(url)
                        } else {
                            UIApplication.shared.openURL(url)
                        }
                    } else {
                        ZMToast.showToast(title: "获取链接失败")
                    }
                }).disposed(by: self.disposeBag)
            } else if cate == .lianlian {
                if LoginService.shared.checkLogin() == false {return}
                ZMToast.showActivity()
                HomeAPI.lianlian([:]).rxRequest(type: String.self).subscribe(onNext:{ [unowned self] resp in
                    ZMToast.hiddenActivity()
                    if let url = URL(string: resp) {
                        if #available(iOS 10, *) {
                            UIApplication.shared.open(url)
                        } else {
                            UIApplication.shared.openURL(url)
                        }
                    } else {
                        ZMToast.showToast(title: "获取链接失败")
                    }
                }).disposed(by: self.disposeBag)
            } else {
                ZMToast.showToast(title: "敬请期待")
            }
        }
        
        someItemView.onClickCallback = {[weak self] type in
            guard let self = self else {return}
            if type == 0 {
                let vc = ArticleDetail()
                self.navigationController?.pushViewController(vc, animated: true)
            } else if type == 1 {
                if LoginService.shared.checkLogin() == false {return}
                router.push("xm://main/Mine/invite")
            } else if type == 2 {
                if AppHelper.appVerify() {
                    let vc = CateGoodsList()
                    vc.type = .taobao
                    self.navigationController?.pushViewController(vc, animated: true)
                } else {
                    if LoginService.shared.checkLogin() == false {return}
                    let vc = GameWeb()
                    let url = getgameUrl(userId: ZMAppShareData.share.safeUserId)
                    UIPasteboard.general.string = url
                    vc.url = url
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
        }
        
        navView.signButton.rx.tap.subscribe(onNext:{ [unowned self] resp in
            if LoginService.shared.checkLogin() == false {return}
            ZMToast.showActivity()
            HomeAPI.signConfig.rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                if JSON(resp)["signInSwitch"].intValue == 1 {
                    router.push("xm://main/Home/sign")
                } else {
                    ZMToast.showToast(title: "签到维护中")
                }
            }).disposed(by: self.disposeBag)
        }).disposed(by: disposeBag)
        
        navView.changeBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            if LoginService.shared.checkLogin() == false {return}
            router.push("xm://main/Home/change_link")
        }).disposed(by: disposeBag)
        
        bannerView.banner.delegate = self
        
        ZMAppShareData.share.userInfo.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {
                self.loginView.isHidden = false
                self.view.bringSubviewToFront(self.loginView)
                return
            }
            self.loginView.isHidden = true
        }).disposed(by: disposeBag)
        
        userHeaderView.redView.zm.addTap(target: self, selector: #selector(onRedBag))
        
        RedBagService.shared.redBagData.subscribe(onNext:{ [unowned self] resp in
            // 没有信息就隐藏展示
            if AppHelper.appVerify() {
                self.userHeaderView.redView.isHidden = true
                return
            }
            guard let resp = resp else {
                self.userHeaderView.redView.isHidden = true
                return
            }
            self.userHeaderView.redView.isHidden = resp.now == nil && resp.wait == nil && resp.next == nil
            self.pagingView.reloadData()
        }).disposed(by: disposeBag)
    }
    
    // 红包点击
    @objc func onRedBag() {
        RedBagService.shared.goRedBagVC()
    }
    
    func preferredPagingView() -> JXPagingView {
        let page = JXPagingView.init(delegate: self)
        return page
    }
    
    func preferredPagingViewVC() -> [ZMViewController] {
        var arr = [ZMViewController]()
        for m in cateArr {
            switch m.type {
            case .jd:
                let vc = HomeJDListVC()
                vc.openHeaderRefresh = true
                arr.append(vc)
                break
            case .pdd:
                let vc = HomePDDListVC()
                vc.openHeaderRefresh = true
                arr.append(vc)
                break
            default:
                let vc1 = HomeListVC()
                vc1.type = m.type
                vc1.openHeaderRefresh = true
                arr.append(vc1)
                break
            }
        }
        return arr
    }
    
    func loadBanner() {
        ZMUtil.listRequest(type: HomeModels.BannerInfo.self, api: HomeAPI.banner) { resp in
            if resp.code == .success, let data = resp.data {
                self.bannerView.isHidden = data.count == 0
                self.bannerInfos = data
                self.bannerView.banner.imageURLStringsGroup = data.map({$0.img})
            }
        }
    }
    
    @IBAction func onLogin(_ sender: Any) {
       _ = LoginService.shared.checkLogin()
    }
    
    //MARK: --------------------delegate--------------------
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
        if bannerInfos.count <= index {
            return
        }
        let data = bannerInfos[index]
        // 跳转类型，0不跳转，1内部页面，2外部链接，3申请合伙人
        if data.urlType == 0 {
            
        } else if data.urlType == 1 {
            let web = ZMWebViewVC()
            web.htmlStr = data.content
            web.title = data.title
            self.navigationController?.pushViewController(web, animated: true)
        } else if data.urlType == 2 {
            guard let url = URL.init(string: data.urlHtml) else {return}
            UIApplication.shared.open(url)
        } else if data.urlType == 3 {
            if LoginService.shared.checkLogin() == false {return}
            router.push("xm://main/Partner/index")
        }
    }
}

extension HomeVC_V2 : JXPagingViewDelegate {
    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        
        return vcs[index] as! JXPagingViewListViewDelegate
    }
    
    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
//        let c = userHeaderView.homeCate.estimateHeight
//        let height = userHeaderView.bannerView.estimateHeight + 12 + c + 12 + userHeaderView.poolView.estimateHeight + 12 + userHeaderView.homeTaskView.estimateHeight + 20
        let h = userHeaderView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
        return Int(h.height)
//        return Int( + 12 + userHeaderView.homeCate.estimateHeight + 12 + userHeaderView.poolView.estimateHeight + 12 + userHeaderView.homeTaskView.estimateHeight)
    }

    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return userHeaderView
    }

    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return headerInSectionHeight
    }

    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return segmentedView
    }

    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return cateArr.count
    }
}

extension HomeVC_V2 : JXPagingMainTableViewGestureDelegate {
    func mainTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        //禁止segmentedView左右滑动的时候，上下和左右都可以滚动
        if otherGestureRecognizer == segmentedView.collectionView.panGestureRecognizer {
            return false
        }
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
    }
}



